package com.lunago.agent.service.impl;

import com.lunago.agent.mapper.UserPermiumMapper;
import com.lunago.agent.pojo.entity.UserPermium;
import com.lunago.agent.pojo.entity.UserPermiumExample;
import com.lunago.agent.service.UserPermiumService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class UserPermiumServiceImpl implements UserPermiumService {

    @Autowired
    private UserPermiumMapper userPermiumMapper;

    @Override
    public void updateUserPermiumStatus(Long userId, Integer orderGemsLevelId) {
        // 通过userId查询信息
        UserPermiumExample example = new UserPermiumExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<UserPermium> list = userPermiumMapper.selectByExample(example);
        if (list == null || list.size() == 0) {
            // 插入一条新数据
            UserPermium userPermium = new UserPermium();
            userPermium.setUserId(userId);
            userPermium.setStatus(1);
            userPermium.setOrderGemsLevelId(orderGemsLevelId);
            userPermium.setStartTime(new Date());
            // 设置结束时间是一个月以后, 使用Calendar实现
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, 1);
            userPermium.setEndTime(calendar.getTime());
            userPermiumMapper.insert(userPermium);
        }else {
            UserPermium userPermium = list.get(0);
            userPermium.setStatus(1);
            userPermium.setOrderGemsLevelId(orderGemsLevelId);
            userPermium.setStartTime(new Date());
            // 设置结束时间是一个月以后, 使用Calendar实现
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, 1);
            userPermium.setEndTime(calendar.getTime());
            userPermiumMapper.updateByPrimaryKeySelective(userPermium);
        }
    }

    @Override
    public UserPermium queryUserPermiumByUserId(Long userId) {
        UserPermiumExample example = new UserPermiumExample();
        example.createCriteria().andUserIdEqualTo(userId);
        List<UserPermium> list = userPermiumMapper.selectByExample(example);
        if (list != null && list.size() > 0) {
            UserPermium item = list.get(0);
            // 判断当前时间是否已经超过enddate
            if (item.getEndTime().getTime() < System.currentTimeMillis()) {
                // 已经过期，修改状态
                item.setStatus(0);
                userPermiumMapper.updateByPrimaryKeySelective(item);
            }
            return item;
        }
        return null;
    }

}
